




/** 文件处理工具 */
export class FileUtils {
    /** 文件转换base64 */
    public static async readAsBase64(file: File) {
        return new Promise<string>((resolve) => {
            const reader = new FileReader();
            // 当读取操作成功完成时触发
            reader.onload = function (e) {
                const base64Text = e.target?.result; // 这是Base64编码的字符串
                if (typeof base64Text === 'string') {
                    resolve(base64Text);
                } else {
                    resolve(''); // 解决null的情况，或者可以reject一个错误
                }
            };
            // 将文件读取为Data URL（即Base64编码的字符串）
            reader.readAsDataURL(file);
        });

    }

    /** 文件下载 */
    public static downloadFile(file: File, fileName?: string) {
        const a = document.createElement('a');
        a.href = URL.createObjectURL(file);
        a.download = fileName || file.name;
        a.click();
        URL.revokeObjectURL(a.href);
    }

    /** 文件地址转换为File 注意跨域 */
    public static async urlToFile(url: string, fileName?: string): Promise<File> {
        const res = await fetch(url);
        const blob = await res.blob();
        const file = new File([blob], fileName || url.substring(url.lastIndexOf('/') + 1), {
            type: blob.type,
        });
        return file;
    }

    /** 文件地址转换为blobUrl 注意跨域 */
    public static async urlToBlobUrl(url: string): Promise<string> {
        const res = await fetch(url);
        const blob = await res.blob();
        const blobUrl = window.URL.createObjectURL(blob);
        return blobUrl;
    }


    /** 根据文件地址下载 */
    public static async downloadFileByUrl(url: string, name?: string) {
        if (name) {
            const blobUrl = await FileUtils.urlToBlobUrl(url);
            const a = document.createElement('a');
            a.href = blobUrl;
            a.target = '_blank';
            a.download = name;
            a.click();
            URL.revokeObjectURL(a.href);
        } else {
            window.open(url);
        }
    }
}